﻿HmJS.$Import('core.core');

/*
---
name: String.UTF-8
version: 0.3-1
description: String UTF8 encoding.
license: MIT-style
download: http://mootools.net/forge/p/string_cryptography
source: http://github.com/sixtyseconds/mootools-string-cryptography
authors: [Christopher Pitt, Enrique Erne]
requires: 
- Core/String
provides: [String.toUTF8, String.fromUTF8]
...
*/

HmJS.register('crypt.string.cryptographyutf8', function ($ns) {

	var toUTF8 = function (string) {
		var a = 0,
				result = '',
				code = String.fromCharCode,
				string = string.replace(/\r\n/g, "\n");

		for (a = 0; b = string.charCodeAt(a); a++) {
			if (b < 128) {
				result += code(b);
			} else if ((b > 127) && (b < 2048)) {
				result += code((b >> 6) | 192);
				result += code((b & 63) | 128);
			} else {
				result += code((b >> 12) | 224);
				result += code(((b >> 6) & 63) | 128);
				result += code((b & 63) | 128);
			}
		}

		return result;
	};

	var fromUTF8 = function (string) {
		var a = 0,
				len = string.length,
				result = '',
				c1 = c2 = c3 = 0;

		while (a < len) {
			c1 = string.charCodeAt(a);

			if (c1 < 128) {
				result += String.fromCharCode(c1);
				a++;
			} else if ((c1 > 191) && (c1 < 224)) {
				c2 = string.charCodeAt(a + 1);
				result += String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
				a += 2;
			} else {
				c2 = string.charCodeAt(a + 1);
				c3 = string.charCodeAt(a + 2);
				result += String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				a += 3;
			}
		}

		return result;
	};

	String.implement({
		'toUTF8': function () {
			return toUTF8(this);
		},
		'fromUTF8': function () {
			return fromUTF8(this);
		}
	});

});
